﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using DaInterFace;
using DaInterFace.SYN;
using DaInterFace.SYN.E01;

namespace E01
{
    /// <summary>
    /// 同步销售返利
    /// </summary>
    public class A10 : ISYNChildSet
    {
        public void Code(ISYN handler, CodeResult result, SYNRight user, SerialType st, String parameter)
        {

            List<E01A10E> E = new List<E01A10E>();

            E01A10P P = (E01A10P)handler.Serial.Deserialize(st, typeof(E01A10P), parameter);
            if (!P.ListAdjustCal.Equals("[]"))
            {
                E = (List<E01A10E>)handler.Serial.Deserialize(st, typeof(List<E01A10E>), P.ListAdjustCal);
            }
           
            try
            {
                SqlParameter[] sps = new SqlParameter[8 + E.Count * 9];
                sps[0] = new SqlParameter("@ID", SqlDbType.NVarChar, 50);
                sps[0].Value = P.ID;
                sps[1] = new SqlParameter("@Number", SqlDbType.NVarChar, 50);
                sps[1].Value = P.Number;
                sps[2] = new SqlParameter("@MakeTime", SqlDbType.DateTime);
                sps[2].Value = Convert.ToDateTime(P.MakeTime);
                sps[3] = new SqlParameter("@CheckTime", SqlDbType.DateTime);
                sps[3].Value = Convert.ToDateTime(P.CheckTime);   
                sps[4] = new SqlParameter("@AdjustMode", SqlDbType.Int);
                sps[4].Value = P.AdjustMode;
                sps[5] = new SqlParameter("@AdjustNum", SqlDbType.Decimal);
                sps[5].Value = P.AdjustNum;
                sps[6] = new SqlParameter("@Remark", SqlDbType.NVarChar, 50);
                sps[6].Value = P.Remark;
                sps[7] = new SqlParameter("@MultiCheckStatus", SqlDbType.Int);
                sps[7].Value = P.MultiCheckStatus;

                for (int i = 0; i < E.Count; i++)
                {
                    sps[8 + 9 * i] = new SqlParameter("@AccountNo" + i.ToString(), SqlDbType.NChar, 50);
                    sps[8 + 9 * i].Value = E[i].AccountNo;
                    sps[9 + 9 * i] = new SqlParameter("@Num" + i.ToString(), SqlDbType.Decimal);
                    sps[9 + 9 * i].Value = E[i].Num;
                    sps[10 + 9 * i] = new SqlParameter("@RawPolicy" + i.ToString(), SqlDbType.NChar, 50);
                    sps[10 + 9 * i].Value = E[i].RawPolicy;
                    sps[11 + 9 * i] = new SqlParameter("@RawPrice" + i.ToString(), SqlDbType.Decimal);
                    sps[11 + 9 * i].Value = E[i].RawPrice;
                    sps[12 + 9 * i] = new SqlParameter("@AdjustPrice" + i.ToString(), SqlDbType.Decimal);
                    sps[12 + 9 * i].Value = E[i].AdjustPrice;
                    sps[13 + 9 * i] = new SqlParameter("@SourceISN" + i.ToString(), SqlDbType.NChar, 50);
                    sps[13 + 9 * i].Value = E[i].SourceISN;
                    sps[14 + 9 * i] = new SqlParameter("@Index" + i.ToString(), SqlDbType.Int);
                    sps[14 + 9 * i].Value = E[i].Index;
                    sps[15 + 9 * i] = new SqlParameter("@BillFID" + i.ToString(), SqlDbType.NChar, 50);
                    sps[15 + 9 * i].Value = E[i].BillFID;
                    sps[16 + 9 * i] = new SqlParameter("@BillNo" + i.ToString(), SqlDbType.NChar, 50);
                    sps[16 + 9 * i].Value = E[i].BillNo;
                    

                }

                StringBuilder sql = new StringBuilder();
                sql.Append(" SET NOCOUNT ON\r\n");
                sql.Append("DECLARE @Type AS  NVARCHAR(50) ");
                sql.Append("DECLARE @ErrorCount AS INT ");
                sql.Append("SET @ErrorCount=0 ");

                sql.Append(" DECLARE @TotalTons INT\n\r ");
                sql.Append(" DECLARE @RebateAmount INT\n\r ");
                sql.Append(" SET @TotalTons = 0  \r\n");
                sql.Append(" SET @RebateAmount = 0  \r\n");
                for (int i = 0; i < E.Count; i++)
                {
                    sql.Append(" SET @TotalTons =@TotalTons + @Num" + i.ToString() + " \r\n");
                    sql.Append(" SET @RebateAmount =@RebateAmount + (@RawPrice" + i.ToString() + " - @AdjustPrice" + i.ToString() + ")* @Num" + i.ToString() + "\r\n");

                }
                sql.Append("DECLARE @FID INT\r\n SET @FID = IsNull((SELECT FID FROM KEW_SalesRebate WHERE FText2 =@ID),0)\r\n");

                sql.Append("BEGIN TRAN ");
                
                sql.Append("DECLARE @Count INT\r\n SET @Count=IsNull((SELECT 1 FROM KEW_SalesRebate WHERE FBillNo=@Number),0)");
                sql.Append("IF @Count>0 BEGIN\r\n");
                sql.Append("  UPDATE KEW_SalesRebate SET FComboBox=@AdjustMode,FDecimal=@TotalTons,FDecimal2=@AdjustNum,FDecimal5=@RebateAmount,FTime=@MakeTime,FTime1=@CheckTime,FNOTE=@Remark WHERE FBillNo=@Number\r\n");
                sql.Append("  SET @ErrorCount=@ErrorCount+@@ERROR ");
                sql.Append("  SET @Type ='U'\r\n");
                sql.Append("END ELSE BEGIN\r\n");
                sql.Append("  EXEC GetICMaxNum 'KEW_SalesRebate',@FID OUTPUT\r\n");
                sql.Append("  INSERT INTO KEW_SalesRebate ([FClassTypeID],[FID],[FBillNo],[FComboBox],[FDecimal],[FDecimal2],[FDecimal5],[FTime],[FTime1],[FNOTE],[FBiller],[FUser],[FMultiCheckStatus],[FText2]) ");
                sql.Append("  VALUES (236900150,@FID,@Number,@AdjustMode,@TotalTons,@AdjustNum,@RebateAmount,@MakeTime,@CheckTime,@Remark,0,0,@MultiCheckStatus,@ID)\r\n");
                sql.Append("  SET @ErrorCount=@ErrorCount+@@ERROR ");
                sql.Append("  SET @Type ='I'\r\n");
                sql.Append("END \r\n");
                sql.Append("  DECLARE @SalesInfoFID INT\r\n ");
                sql.Append("  DECLARE @SalesInfoFBillNo INT\r\n ");

                for (int i = 0; i < E.Count; i++)
                {
                    sql.Append("IF (SELECT COUNT(1) FROM KEW_SalesRebateEntry WHERE FID =@FID AND FIndex=@Index" + i.ToString() + " ) > 0 BEGIN\r\n ");
                    sql.Append("  UPDATE KEW_SalesRebateEntry SET FDecimal3=@RawPrice" + i.ToString() + " ,FDecimal4=@AdjustPrice" + i.ToString() + ",FText1=@RawPolicy" + i.ToString() + ", FText=@AccountNo" + i.ToString() + ",FID_SRC=@BillFID" + i.ToString() + ",FBillNo_SRC=@BillNo" + i.ToString() + " WHERE FID =@FID AND FIndex=@Index" + i.ToString() + " \r\n");
                    sql.Append("END ELSE BEGIN\r\n");
                    sql.Append("  INSERT INTO KEW_SalesRebateEntry ([FClassID_SRC],[FID],[FIndex],[FDecimal1],[FDecimal3],[FDecimal4],[FText1],[FText],[FID_SRC],[FBillNo_SRC]) VALUES (236900103,@FID,@Index" + i.ToString() + ",@Num" + i.ToString() + ",@RawPrice" + i.ToString() + ",@AdjustPrice" + i.ToString() + ",@RawPolicy" + i.ToString() + ",@AccountNo" + i.ToString() + ",@BillFID" + i.ToString() + ",@BillNo" + i.ToString() + ")\r\n ");
                    sql.Append("END \r\n");
                    sql.Append("  SET @ErrorCount=@ErrorCount+@@ERROR ");

                }
                //执行存储过程 审核人
                sql.Append("  EXEC KEW_SALES_APPLYREBATE @FID,'0' \r\n");
                sql.Append("IF @ErrorCount=0 AND (SELECT COUNT(1) FROM KEW_SalesRebate WHERE FBillNo=@Number)=1 ");
                sql.Append("BEGIN ");
                sql.Append("SELECT @Type,@FID\r\n ");
                sql.Append("COMMIT TRAN ");
                sql.Append("END ");
                sql.Append("ELSE BEGIN ");
                sql.Append("SELECT 'FALSE','事务出错回滚' ");
                sql.Append("ROLLBACK TRAN ");
                sql.Append("END ");

                sql.Append("SET NOCOUNT OFF\r\n");
                Recordset rs = handler.Data.ExeProcedure(P.BaseNo, sql.ToString(), sps);
                if (rs.Enable)
                {
                    if (rs.Data.Tables[0].Rows[0][0].ToString() == "U")
                    {
                        result.Result = EnumResult.Update;
                        result.Content = rs.Data.Tables[0].Rows[0][1].ToString();
                    }
                    else
                    {
                        result.Result = EnumResult.Insert;
                        result.Content = rs.Data.Tables[0].Rows[0][1].ToString();
                    }
                    result.Message = String.Format("销售返利同步完成:{0},{1}", P.Number, result.Result.ToString());
                }
                else
                {
                    result.Result = EnumResult.None;
                    result.Message = String.Format("销售返利同步失败:{0}", rs.Message);
                }
            }
            catch (Exception ex)
            {
                result.Result = EnumResult.None;
                result.Message = String.Format("销售返利同步失败:{0}", ex.Message);
            }
        }

    }

    /// <summary>
    /// 销售返利
    /// </summary>
    public class E01A10P
    {
        /// <summary>
        /// 账套编号
        /// </summary>
        public String BaseNo;
        /// <summary>
        /// 三方内码
        /// </summary>
        public String ID;
        /// <summary>
        /// 三方编号
        /// </summary>
        public String Number;
        /// <summary>
        /// 调整方式
        /// </summary>
        public int AdjustMode;
        /// <summary>
        /// 调整数值
        /// </summary>
        public decimal AdjustNum;
        /// <summary>
        /// 制单时间
        /// </summary>
        public String MakeTime;
        /// <summary>
        /// 审核时间
        /// </summary>
        public String CheckTime;
        /// <summary>
        /// 备注
        /// </summary>
        public String Remark;
        /// <summary>
        /// 审批流程状态（）
        /// </summary>
        public int MultiCheckStatus;
        /// <summary>
        /// 计量单
        /// </summary>
        public String ListAdjustCal;

    }
    /// <summary>
    /// 销售返利-计量单
    /// </summary>
    public class E01A10E
    {
        /// <summary>
        ///计量单顺序号
        /// </summary>
        public int Index;
        /// <summary>
        /// 榜单FID
        /// </summary>
        public String BillFID;
        /// <summary>
        /// 榜单FBillNo
        /// </summary>
        public String BillNo;
        /// <summary>
        /// 账户编号
        /// </summary>
        public String AccountNo;
        /// <summary>
        /// 数量
        /// </summary>
        public Decimal Num;
        /// <summary>
        /// 原始价格政策
        /// </summary>
        public String RawPolicy;
        /// <summary>
        /// 原始单价
        /// </summary>
        public decimal RawPrice;
        /// <summary>
        /// 调整单价
        /// </summary>
        public decimal AdjustPrice;
        /// <summary>
        /// 源单内码
        /// </summary>
        public String SourceISN;

    }
   
}
